package edu.cmu.scs.hci.TagIt;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class SimpleTagger extends Activity {

	private long mRowId;
	private PhotosDbAdapter mDb;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			mRowId = (Long) savedInstanceState.getSerializable(PhotosDbAdapter.KEY_ID);
		}
		else {
			Bundle extras = getIntent().getExtras();
			mRowId = extras.getLong(PhotosDbAdapter.KEY_ID);
		}
		mDb = new PhotosDbAdapter(this);
		mDb.open();
		setContentView(R.layout.simple_tagger);
		fillData();
		Button button = (Button) findViewById(R.id.new_tag_confirm);
		button.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {
				EditText new_tag = (EditText) findViewById(R.id.new_tag);
				if (new_tag.getText().length() == 0) {
					return;
				}
				String tag = new_tag.getText().toString();
				mDb.addTagToPhoto(mRowId, tag);
				new_tag.setText("");
				fillData();
			}
		});
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putSerializable(PhotosDbAdapter.KEY_ID, mRowId);
	}
	
	private void fillData() {
		Cursor c = mDb.getTags(mRowId);
		String [] from = new String [] { PhotosDbAdapter.KEY_TAG_CONTENT };
		int [] to = new int[] { R.id.tag1 };
		
		ListView listV = (ListView) findViewById(R.id.tagList);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.tag_row, c, from, to);
		listV.setAdapter(adapter);
	}

}
